package cn.edu.sdjzu.xg.eagle.controller;


import cn.edu.sdjzu.xg.eagle.entity.User;
import cn.edu.sdjzu.xg.eagle.factory.ServiceFactory;
import cn.edu.sdjzu.xg.eagle.service.UserServiceInterface;
import cn.edu.sdjzu.xg.eagle.util.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login.ctl")
public class LoginCtrl extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        String  user_json = JSONUtil.getJSON(request);
        User userToLogin = JSON.parseObject(user_json, User.class);
        JSONObject message = new JSONObject();
        try {
            ServiceFactory.getService(UserServiceInterface.class,"UserServiceImpl").login(userToLogin);
            if(userToLogin.getId()==null){
                message.put("message","用户不存在/密码错误");
                message.put("code","500");
                response.getWriter().println(message.toJSONString(message));
            }else{
                message.put("message","操作成功");
                message.put("code","200");
                response.getWriter().println(message.toJSONString(message));
            }
        } catch (SQLException e) {
            message.put("message","数据库操作异常");
            response.getWriter().println(message.toJSONString(message));
            e.printStackTrace();
        }catch (Exception e){
            message.put("message","网络异常");
            response.getWriter().println(message.toJSONString(message));
        }
    }
}
